<template>
  <div>
    <el-form :inline="true">
      <el-form-item :label="$t('startDate')">
        <el-date-picker
          v-model="startDate"
          type="datetime"
          :placeholder="$t('startDate')"
          align="right"
          :picker-options="pickerOptions1"
          value-format="timestamp"
        />
      </el-form-item>
      <el-form-item :label="$t('endDate')">
        <el-date-picker
          v-model="endDate"
          type="datetime"
          :placeholder="$t('endDate')"
          align="right"
          :picker-options="pickerOptions1"
          value-format="timestamp"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="listUserLoginLog"
        >{{ $t('search') }}
        </el-button>
      </el-form-item>
    </el-form>
    <div
      id="user-trajectory"
      style="height: calc(100vh - 200px); width: 100%; overflow: hidden;"
    />
  </div>
</template>

<script>
import { listUserLoginLog } from '@/api/auth/authUserLoginLogApi'
import { makeMap, makeMarket } from '@/util/mapTool'

let map = null
export default {
  name: 'LoginMap',
  props: {
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      map: null,
      startDate: 0,
      endDate: 0,
      pickerOptions1: {
        shortcuts: [
          {
            text: this.$t('today'),
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: this.$t('today'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: this.$t('a') + this.$t('week') + this.$t('ago'),
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  destroyed() {
    map.destroy()
    map = null
  },
  mounted() {
    const timestamp = new Date().getTime()
    this.startDate = timestamp - 7 * 24 * 60 * 60 * 1000
    this.endDate = timestamp + 4 * 60 * 60 * 1000
    this.listUserLoginLog()
  },
  methods: {
    listUserLoginLog() {
      listUserLoginLog({
        startDate: Math.round(this.startDate / 1000),
        endDate: Math.round(this.endDate / 1000),
        userId: this.userId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.initChart(data)
        }
      })
    },
    initChart(data) {
      if (!data || data.length <= 0) {
        return
      }
      const one = data[0]
      map = makeMap(document.getElementById('user-trajectory'), one.lat, one.lng)
      data.forEach(item => {
        makeMarket(map, item.lat, item.lng)
      })
    }
  }
}
</script>
